package com.beyondsoft.mcms.web;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.domain.Users;
import com.beyondsoft.mcms.reference.AuthRole;

@RequestMapping("/userses")
@Controller
@RooWebScaffold(path = "userses", formBackingObject = Users.class)
@RooWebFinder
public class UsersController {

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        Users user = new Users();
        user.setEnabled(true);
        populateCreateForm(uiModel, user);
        return "userses/create";
    }

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Users users, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateCreateForm(uiModel, users);
            return "userses/create";
        }
        if (!Users.findUsersesByUsernameEquals(users.getUsername()).getResultList().isEmpty()) {
            bindingResult.rejectValue("username", "users_field_username_exist");
            populateCreateForm(uiModel, users);
            return "userses/create";
        }
        uiModel.asMap().clear();
        users.setCreateDate(new Date());
        users.setCreatedBy(CommonUtils.getCurrentUsername());
        users.setPassword(CommonUtils.encodingPWD(users.getPassword()));
        users.persist();
        return "redirect:/userses/" + encodeUrlPathSegment(users.getId().toString(), httpServletRequest);
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Users users, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, users);
            return "userses/update";
        }
        uiModel.asMap().clear();
        users.setUpdateDate(new Date());
        users.setUpdatedBy(CommonUtils.getCurrentUsername());
        users.merge();
        return "redirect:/userses/" + encodeUrlPathSegment(users.getId().toString(), httpServletRequest);
    }

    void populateCreateForm(Model uiModel, Users users) {
        uiModel.addAttribute("users", users);
        List<AuthRole> authroles = new ArrayList<AuthRole>();
        authroles.add(AuthRole.ADMIN);
        uiModel.addAttribute("authroles", authroles);
    }

    void populateEditForm(Model uiModel, Users users) {
        uiModel.addAttribute("users", users);
        uiModel.addAttribute("authroles", Arrays.asList(AuthRole.values()));
    }

    @RequestMapping(params = { "find=ByUsernameLikeAndAuthority", "form" }, method = RequestMethod.GET)
    public String findUsersesByUsernameLikeAndAuthorityForm(Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute("username", null);
        request.getSession().setAttribute("authority", null);
        return findUsersesByUsernameLikeAndAuthority(null, null, uiModel);
    }

    @RequestMapping(params = "find=ByUsernameLikeAndAuthority", method = RequestMethod.GET)
    public String findUsersesByUsernameLikeAndAuthority(@RequestParam(value="username", required=false) String username, 
    		@RequestParam(value="authority", required=false) AuthRole authority, Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int sizeNo = size == null ? 10 : Integer.valueOf(size);
        int pageNo = page == null ? 1 : Integer.valueOf(page);
        if (page != null && size != null) {
        	username = (String) request.getSession().getAttribute("username");
            authority = (AuthRole) request.getSession().getAttribute("authority");
        } else {
            request.getSession().setAttribute("username", username);
            request.getSession().setAttribute("authority", authority);
        }
        uiModel.addAttribute("username", username);
        uiModel.addAttribute("authority", authority);
        return list(pageNo, sizeNo, uiModel);
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        uiModel.addAttribute("authroles", CommonUtils.getEnumAuthRole());
        String username = (String) uiModel.asMap().get("username");
        AuthRole authority = (AuthRole) uiModel.asMap().get("authority");
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        float nrOfPages = 0.0f;
        List<Users> users = Users.findUsersesByUsernameLikeAndAuthority(username, authority).getResultList();
        int lastResult = (users.size() > (sizeNo + firstResult)) ? (sizeNo + firstResult) : users.size();
        uiModel.addAttribute("userses", users.subList(firstResult, lastResult));
        nrOfPages = (float) users.size() / sizeNo;
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        uiModel.addAttribute("find", "ByUsernameLikeAndAuthority"); // differ non-query request
        uiModel.addAttribute("selectQueryIds", authority == null ? AuthRole.SUPERVISOR : authority);
        return "userses/list";
    }

    @RequestMapping(value = "managepwd")
    public String managepwd(Model uiModel, HttpServletRequest request) {
        String adminPassword = request.getParameter("adminPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        String username = request.getParameter("username");
        uiModel.addAttribute("username", username);
        Users supervisor = CommonUtils.getCurrentUser();
        String userPassword = supervisor.getPassword();
        if (!userPassword.equals(CommonUtils.encodingPWD(adminPassword))) {
            uiModel.addAttribute("backMessage", "changepwd_adminpassword_error");
            return "userses/managepwd";
        }
        if (!newPassword.equals(confirmPassword)) {
            uiModel.addAttribute("backMessage", "changepwd_confirmpassword_error");
            return "userses/managepwd";
        }
        Users user = Users.findUsersesByUsernameEquals(username).getSingleResult();
        user.setPassword(CommonUtils.encodingPWD(newPassword));
        user.merge();
        uiModel.addAttribute("backMessage", "changepwd_success");
        return "userses/managepwd";
    }

    @RequestMapping(value = "pwdindex")
    public String pwdindex(Model uiModel, HttpServletRequest request) {
        String username = request.getParameter("username");
        uiModel.addAttribute("username", username);
        return "userses/managepwd";
    }
}
